package fit.conceptmap.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import fit.conceptmap.beans.UserBean;
import fit.conceptmap.services.IUserService;

@Controller
@SessionAttributes({"username", "role" })
public class UserController {
	
	@Autowired
	IUserService userService;
	
	private static final Logger logger = Logger.getLogger(UserController.class);
	
	// 1. Json
	/*@RequestMapping(value="/register", method=RequestMethod.POST, headers="Accept=application/json")
	@ResponseBody
	public UserBean register(@RequestBody UserBean user) {
		if(userService.addNewUser(user))
			logger.info("Add new user success!");;
		return user;
	}*/
	
	// 2. Submit form
	/*@RequestMapping(value="/register", method=RequestMethod.POST)
	public String register(@RequestParam("username") String username, @RequestParam("password") String password
			, @RequestParam("fullname") String fullname, @RequestParam("birthdate") String birthdate) {
		UserBean user = new UserBean();
		user.setIdUser(username);
		user.setPassword(password);
		user.setFullName(fullname);
		user.setDateBirth(birthdate);
		if(userService.addNewUser(user))
			logger.info("Add new user success!");;
		return "register";
	}*/
	
	// 3
	@RequestMapping(value="/register/{username}/{password}/{fullName}/{dateBirth}", method=RequestMethod.GET)
	@ResponseBody
	public UserBean register(@PathVariable("username") String username, @PathVariable("password") String password
			, @PathVariable("fullname") String fullname, @PathVariable("birthdate") String birthdate) {
		UserBean user = new UserBean();
		user.setIdUser(username);
		user.setPassword(password);
		user.setFullName(fullname);
		user.setDateBirth(birthdate);
		if(userService.addNewUser(user))
			logger.info("Add new user success!");;
		return user;
	}
	
	@RequestMapping(value="/updateuser/{password}/{fullName}", method=RequestMethod.GET)
	@ResponseBody
	public UserBean updateProfile(@PathVariable("password") String password
			, @PathVariable("fullName") String fullname,
			@ModelAttribute("username") String username) {
		UserBean user = new UserBean();
		user.setIdUser(username);
		user.setPassword(password);
		user.setFullName(fullname);
		if(userService.updateUser(user))
			logger.info("Add new user success!");;
		return user;
	}
}
